package org.csu.softwaremetrics_demo.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileUtils {
	private static ColorLoggerUtils logger = new ColorLoggerUtils(FileUtils.class);
	//Get all directories from the directory at the given path.
	public static String[] getAllDirs(String path) {
		try {
			return Files.walk(Paths.get(path))
					.filter(Files::isDirectory)
					.filter(x -> !isGitDir(x.toAbsolutePath().toString()))
					.map(x -> x.toAbsolutePath().toString())
					.toArray(String[]::new);
		} catch(Exception e) {
			throw new RuntimeException(e);
		}
	}

	//Get all java class files from the directory at the given path.
	public static String[] getAllJavaFiles(String path) {
		return getAllFiles(path, "java");
	}

	//Get all jars from the directory at the given path.
	public static String[] getAllJars(String path) {
		return getAllFiles(path, "jar");
	}

	//Get all files from of the given file ending from the directory at the given path.
	private static String[] getAllFiles(String path, String ending){
		try {
			return Files.walk(Paths.get(path))
					.filter(Files::isRegularFile)
					.filter(x -> !isGitDir(x.toAbsolutePath().toString()))
					.filter(x -> x.toAbsolutePath().toString().toLowerCase().endsWith(ending))
					.map(x -> x.toAbsolutePath().toString())
					.toArray(String[]::new);
		} catch(Exception e) {
			throw new RuntimeException(e);
		}
	}

	//Is the given directory a git repository directory?
	private static boolean isGitDir(String path){
		return path.contains("/.git/");
	}

	/**
	 * 在basePath下保存上传的文件夹
	 *
	 * @param basePath
	 * @param files
	 */
	public static void saveMultiFile(String basePath, MultipartFile[] files) {
		if (files == null || files.length == 0) {
			logger.warn("no files uploaded");
			return;
		} else if (files[0].getOriginalFilename() == null || files[0].getOriginalFilename().equals("")) {
			logger.warn("Empty package: no files to be uploaded");
			return;
		}
		for (MultipartFile file : files) {
			String relativePath = file.getOriginalFilename();
			String filePath = new File(basePath).getAbsolutePath() + "/" + relativePath;
			logger.info("uploading " + relativePath + " to " + filePath + "......");
			makeDir(filePath);
			File dest = new File(filePath);
			try {
				file.transferTo(dest);
				logger.info("successful upload");
			} catch (IllegalStateException | IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 确保目录存在，不存在则创建
	 *
	 * @param filePath
	 */
	private static void makeDir(String filePath) {
		if (filePath.lastIndexOf('/') > 0) {
			String dirPath = filePath.substring(0, filePath.lastIndexOf('/'));
			File dir = new File(dirPath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
		}
	}
}